"""
客户管理视图（后台管理）
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
from django.db.models import Q, Sum, Count
from pecco_site.models import UserProfile
from ..permissions import IsAdminUser
from ..serializers.customer import (
    CustomerListSerializer, CustomerDetailSerializer, CustomerStatsSerializer
)


class CustomerViewSet(viewsets.ModelViewSet):
    """客户管理视图集（后台管理）"""
    queryset = User.objects.filter(is_staff=False).select_related('profile').order_by('-date_joined')
    permission_classes = [IsAuthenticated, IsAdminUser]
    
    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'retrieve' or self.action == 'update' or self.action == 'partial_update':
            return CustomerDetailSerializer
        return CustomerListSerializer
    
    def get_queryset(self):
        """过滤查询集"""
        queryset = super().get_queryset()
        
        # 搜索
        search = self.request.query_params.get('search', '')
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) |
                Q(email__icontains=search) |
                Q(first_name__icontains=search) |
                Q(last_name__icontains=search)
            )
        
        # 状态过滤
        is_active = self.request.query_params.get('is_active')
        if is_active is not None:
            queryset = queryset.filter(is_active=is_active == 'true')
        
        # 订阅过滤
        newsletter_subscribed = self.request.query_params.get('newsletter_subscribed')
        if newsletter_subscribed is not None:
            queryset = queryset.filter(profile__newsletter_subscribed=newsletter_subscribed == 'true')
        
        return queryset
    
    @action(detail=False, methods=['get'])
    def stats(self, request):
        """获取客户统计信息"""
        from pecco_site.models import Order

        total_customers = User.objects.filter(is_staff=False).count()
        active_customers = User.objects.filter(is_staff=False, is_active=True).count()
        newsletter_subscribers = UserProfile.objects.filter(newsletter_subscribed=True).count()

        # 订单和收入统计（只统计已完成的订单）
        completed_orders = Order.objects.filter(status='completed')
        total_orders = completed_orders.count()
        total_revenue = completed_orders.aggregate(total=Sum('total_price'))['total'] or 0

        stats_data = {
            'total_customers': total_customers,
            'active_customers': active_customers,
            'newsletter_subscribers': newsletter_subscribers,
            'total_orders': total_orders,
            'total_revenue': total_revenue,
        }

        serializer = CustomerStatsSerializer(stats_data)
        return Response(serializer.data)
    
    @action(detail=True, methods=['patch'])
    def toggle_active(self, request, pk=None):
        """切换客户激活状态"""
        customer = self.get_object()
        customer.is_active = not customer.is_active
        customer.save()
        
        return Response({
            'message': f'Customer {"activated" if customer.is_active else "deactivated"} successfully',
            'is_active': customer.is_active
        })
    
    @action(detail=True, methods=['post'])
    def reset_password(self, request, pk=None):
        """重置客户密码（管理员功能）"""
        customer = self.get_object()
        new_password = request.data.get('new_password')
        
        if not new_password:
            return Response({
                'error': 'new_password is required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        customer.set_password(new_password)
        customer.save()
        
        return Response({
            'message': 'Password reset successfully'
        })
    
    def destroy(self, request, *args, **kwargs):
        """删除客户（软删除：设置为不激活）"""
        customer = self.get_object()
        customer.is_active = False
        customer.save()
        
        return Response({
            'message': 'Customer deactivated successfully'
        }, status=status.HTTP_200_OK)


